<template>
  <div class="box">
    <div v-if="addressData == undefined">
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-default="onChangeDetail"
      />
    </div>

    <div v-else>
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-default="onChangeDetail"
        :address-info="{
          name: addressData.name,
          tel: addressData.tel,
          isDefault: addressData.isDefault,
          city: city,
          county: county,
          country: country,
          province: province,
          addressDetail: addressDetail
        }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { areaList } from '@vant/area-data'
import { useCounterStore } from '../../api/pinia'
import { ElMessage } from 'element-plus'
const router = useRouter()
const store = useCounterStore()
const data = ref()
// const props = useRoute();
const addressData = ref(JSON.parse(localStorage.getItem('addressData')) || undefined)
console.log(addressData.value)
const city = ref('')
const county = ref('')
const country = ref('')
const province = ref('')
const addressDetail = ref('')
console.log(addressData.value)

if (addressData.value != undefined) {
  const arr = addressData.value.address.split('-')
  console.log(arr)
  province.value = arr[0]
  city.value = arr[1]
  county.value = arr[2]
  addressDetail.value = arr[3]
}
// const;
const flag = ref(localStorage.getItem('status'))
const onSave = (e) => {
  console.log(e)
  if (flag.value == 'get') {
    let obj = {
      id: addressData.value.id,
      name: e.name,
      tel: e.tel,
      address: e.province + '-' + e.city + '-' + e.county + '-' + e.addressDetail,
      isDefault: e.isDefault
    }
    store.updateAddress(obj)
  } else if (flag.value == 'add') {
    let obj = {
      id: new Date().getTime(),
      name: e.name,
      tel: e.tel,
      address: e.province + '-' + e.city + '-' + e.county + '-' + e.addressDetail,
      isDefault: e.isDefault
    }
    store.addAddress(obj)
  }
  router.push('/my/shippingAddress')
}
const onDelete = () => {
  console.log(addressData.value.id)
  store.deleteAddress(addressData.value.id)
  ElMessage('删除成功')
  setTimeout(() => {
    router.push('/my/shippingAddress')
  }, 2000)
}
// 设置默认地址
const onChangeDetail = () => {
  console.log('111')
  store.address.checked = true
}
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
}
</style>
